<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="79px"
    >
      <el-form-item label="收支/分类" prop="amountType">
        <el-cascader :options="cateTreeOptions" @change="handleCascaderChange"
                     :props="{checkStrictly: true}" clearable style="width: 240px;"/>
      </el-form-item>
      <el-form-item label="账单标题" prop="billTitle">
        <el-input
          v-model="queryParams.billTitle"
          placeholder="请输入账单标题"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="账单备注" prop="billRemark">
        <el-input
          v-model="queryParams.billRemark"
          placeholder="请输入账单备注"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="变动账户" prop="accountId">
        <el-select
          v-model="queryParams.accountId"
          placeholder="请选择变动账户"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="item in accountIdOptions"
            :key="item.accountId"
            :label="item.accountName"
            :value="item.accountId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="账单标签" prop="tags">
        <el-select
          v-model="tagsOptionsTemp"
          placeholder="请选择账单标签"
          clearable
          multiple
          filterable
          @change="handleTagChange"
          class="!w-240px"
        >
          <el-option
            v-for="item in tagsOptions"
            :key="item.id"
            :label="item.tag"
            :value="item.tag"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="账单状态" prop="billStatus">
        <el-select
          v-model="queryParams.billStatus"
          placeholder="请选择账单状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BILL_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="账单阶段" prop="billStage">
        <el-select
          v-model="queryParams.billStage"
          placeholder="请选择账单阶段"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BILL_STAGE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="账单类型" prop="billType">
        <el-select
          v-model="queryParams.billType"
          placeholder="请选择账单类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BILL_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="转账去向" prop="transAccountId">
        <el-select
          v-model="queryParams.transAccountId"
          placeholder="请选择变动账户"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="item in accountIdOptions"
            :key="item.accountId"
            :label="item.accountName"
            :value="item.accountId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="账单来源" prop="extBillSource">
        <el-input
          v-model="queryParams.extBillSource"
          placeholder="请输入账单来源"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="是否资产" prop="hasProperty">
        <el-select
          v-model="queryParams.hasProperty"
          placeholder="是否资产"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BILL_YES_OR_NO)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="资产名称" prop="propertyName">
        <el-input
          v-model="queryParams.propertyName"
          placeholder="请输入资产名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="账单时间" prop="billTime">
        <el-date-picker
          v-model="queryParams.billTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['bill:bill:create']"
        >
          <Icon icon="ep:plus" class="mr-5px"/>
          新增
        </el-button>
        <el-button
          type="warning"
          plain
          @click="handleImport"
          v-hasPermi="['bill:bill:export']"
        >
          <Icon icon="ep:upload" /> 导入
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['bill:bill:export']"
        >
          <Icon icon="ep:download" class="mr-5px"/>
          导出
        </el-button>
        <el-button @click="batchDelHandle" type="danger">
          <Icon icon="ep:delete" class="mr-5px"/>
          批量删除
        </el-button>
        <el-button @click="batchTagHandle" type="info">
          <Icon icon="ep:collection-tag" class="mr-5px"/>
          批量打标
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" show-summary :stripe="true" border :show-overflow-tooltip="true"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="操作" align="center" min-width="160" >
        <template #default="scope">
          <el-button circle type="info" size="default" :icon="CopyDocument"
                     @click="openForm('copy', scope.row.id)" v-hasPermi="['bill:bill:update']"/>
          <el-button circle type="primary" size="default" :icon="Edit"
                     @click="openForm('update', scope.row.id)" v-hasPermi="['bill:bill:update']"/>
          <el-button circle type="danger" size="default" :icon="Delete"
                     @click="handleDelete(scope.row.id)" v-hasPermi="['bill:bill:delete']"/>
        </template>
      </el-table-column>

      <el-table-column type="expand">
        <template #default="scope">
          <el-descriptions title="详细信息" :column="3" size="default" border
                           style="width:1200px;margin:10px;">
            <el-descriptions-item>
              <template #label>账单ID</template>
              {{ scope.row.id }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>账单所属模板</template>
              {{ scope.row.templateId }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>账单状态</template>
              <dict-tag :type="DICT_TYPE.BILL_STATUS" :value="scope.row.billStatus"/>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>补充信息</template>
              {{ scope.row.extInfo }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>账单备注</template>
              {{ scope.row.billRemark }}
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions title="外部信息" :column="3" size="default" border
                           style="width:1200px;margin:10px;">
            <el-descriptions-item>
              <template #label>外部说明</template>
              {{ scope.row.extRemark }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>外部付款账户</template>
              {{ scope.row.extFromAccount }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>外部付款人</template>
              {{ scope.row.extFromOwner }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>外部收款账户</template>
              {{ scope.row.extToAccount }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>外部收款人</template>
              {{ scope.row.extToOwner }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>其他</template>
              {{ '-' }}
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions title="资产信息" :column="3" size="default" border
                           style="width:1200px;margin:10px;">
            <el-descriptions-item>
              <template #label>是否为资产</template>
              <dict-tag :type="DICT_TYPE.BILL_YES_OR_NO" :value="scope.row.hasProperty"/>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>资产名称</template>
              {{ scope.row.propertyName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>资产盘点时间</template>
              {{ formatDate(scope.row.propertyCheckTime) }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>资产类别</template>
              <dict-tag :type="DICT_TYPE.PROPERTY_CATE" :value="scope.row.propertyCate"/>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>资产价值</template>
              {{ scope.row.propertyValue }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>资产参数</template>
              {{ scope.row.propertyParam }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>资产备注</template>
              {{ scope.row.propertyRemark }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>资产状态</template>
              <dict-tag :type="DICT_TYPE.PROPERTY_STATUS" :value="scope.row.propertyStatus"/>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>其他</template>
              {{ '-' }}
            </el-descriptions-item>
          </el-descriptions>
        </template>
      </el-table-column>
<!--      <el-table-column label="账单ID" align="center" prop="id" width="100"/>-->
      <el-table-column label="收支类型" align="center" prop="amountType" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BILL_AMOUNT_TYPE" :value="scope.row.amountType"/>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" width="180">
        <template #default="scope">
          {{ scope.row.cate1 }}{{
            scope.row.cate2 !== null ? '/' + scope.row.cate2 : ''
          }}{{ scope.row.cate3 !== null ? '/' + scope.row.cate3 : '' }}
        </template>
      </el-table-column>
      <el-table-column label="账单金额" align="center" prop="billAmount" width="100">
        <template #default="scope">
          ¥{{ scope.row.billAmount }}
        </template>
      </el-table-column>
      <el-table-column label="变动账户" align="center" prop="accountId" width="150">
        <template #default="scope">
          {{ accountMap[scope.row.accountId] }}
        </template>
      </el-table-column>
      <el-table-column label="账单标题" align="center" prop="billTitle" width="220">
        <template #default="scope">
          <el-tooltip
            effect="dark"
            trigger="click"
            :content="scope.row.billRemark"
            placement="top"
          >
            {{ scope.row.billTitle }}
          </el-tooltip>
        </template>
      </el-table-column>


      <el-table-column
        label="账单时间"
        align="center"
        prop="billTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="账单类型" align="center" prop="billType" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BILL_TYPE" :value="scope.row.billType"/>
        </template>
      </el-table-column>
      <el-table-column label="转账去向" align="center" prop="transAccountId" width="100"/>
      <el-table-column label="账单阶段" align="center" prop="billStage" width="90">
        <template #default="scope">
          {{ scope.row.billStage }}
        </template>
      </el-table-column>
      <el-table-column label="账单标签" align="center" prop="tags" width="110">
        <template #default="scope">
          <el-tag
            v-for="(item, index) in scope.row.tags.split('@')"
            :key="index"
            style="margin-right: 5px;"
            type="info"
            size="small"
          >
            {{ item }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="账单来源" align="center" prop="extBillSource" width="100"/>
      <el-table-column label="是否资产" align="center" prop="hasProperty" width="90">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BILL_YES_OR_NO" :value="scope.row.hasProperty"/>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      :page-sizes="[50,60,70,80,90,100]"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BillForm ref="formRef" @success="getList"/>
  <BillImportForm ref="importFormRef" @success="getList" />

</template>

<script setup lang="ts">
import {getStrDictOptions, DICT_TYPE, getIntDictOptions} from '@/utils/dict'
import {dateFormatter, formatDate} from '@/utils/formatTime'
import download from '@/utils/download'
import {BillApi, BillVO} from '@/api/bill/bill'
import BillForm from './BillForm.vue'
import {AccountApi} from '@/api/bill/account'
import {CateApi} from '@/api/bill/bill_cate'
import {
  CopyDocument,
  Delete,
  Edit
} from '@element-plus/icons-vue'
import {TagApi} from '@/api/bill/tag'
import BillImportForm from './BillImportForm.vue'

/** 账单信息 列表 */
defineOptions({name: 'Bill'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<BillVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 50,
  billTitle: undefined,
  billRemark: undefined,
  billAmount: undefined,
  amountType: undefined,
  accountId: undefined,
  cate1: undefined,
  cate2: undefined,
  cate3: undefined,
  tags: undefined,
  templateId: undefined,
  billType: undefined,
  billStage: undefined,
  billStatus: undefined,
  transAccountId: undefined,
  billTime: [],
  extRemark: undefined,
  extFromAccount: undefined,
  extFromOwner: undefined,
  extToAccount: undefined,
  extToOwner: undefined,
  extInfo: undefined,
  extBillSource: undefined,
  extParam: undefined,
  orderNum: undefined,
  hasProperty: undefined,
  propertyName: undefined,
  propertyCheckTime: [],
  propertyCate: undefined,
  propertyValue: undefined,
  propertyParam: undefined,
  propertyRemark: undefined,
  propertyStatus: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const accountIdOptions = ref()
const cateTreeOptions = ref([])
const tagsOptions = ref([])
const tagsOptionsTemp = ref([])
const accountMap = ref({})

/** 用户导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await BillApi.getBillPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const selectionIds = ref<Array<string | number>>([]);
const handleSelectionChange = (selection) => {
  selectionIds.value = selection.map((item) => item.id);
};

const getAccountOptions = async () => {
  const data = await AccountApi.getAccountPage({
    pageNo: 1,
    pageSize: 100,
    hasEnable: 1
  })
  // 将 data 转换为 { id: accountName } 的对象
  accountMap.value = data.list.reduce((acc, item) => {
    acc[item.accountId] = item.accountName  + ' | ' + item.accountOwner;
    return acc;
  }, {});
  // console.log( accountMap.value)
  accountIdOptions.value = data.list
}
const getTagsOptions = async () => {
  const data = await TagApi.getTagPage({
    pageNo: 1,
    pageSize: 100
  })
  tagsOptions.value = data.list
}
const getCateTreeOptions = async () => {
  const data = await CateApi.getCateTree({})
  cateTreeOptions.value = data
}

const handleCascaderChange = (value) => {
  queryParams.amountType = value[0]
  queryParams.cate1 = value[1]
  queryParams.cate2 = value[2]
  // console.log(queryParams)
}
const handleTagChange = (value) => {
  queryParams.tags = value.join('@')
  // console.log(value)
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BillApi.deleteBill(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}
/** 删除按钮操作 */
const batchDelHandle = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await BillApi.deleteBatchBill(selectionIds.value)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}
const batchTagHandle = async () => {
  try {
    if(selectionIds.value.length === 0){
      message.error("请选择账单！")
    }
    await message.confirm("即将为"+selectionIds.value.length+"个账单打标签："+ queryParams.tags)
    // 删除的二次确认
    await BillApi.updateBatchBill(selectionIds.value,{
      tags:queryParams.tags
    })
    message.success("打标成功")
    // 刷新列表
    await getList()
  } catch {
  }
}
/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await BillApi.exportBill(queryParams)
    download.excel(data, '账单信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  getAccountOptions()
  getCateTreeOptions()
  getTagsOptions()
})
</script>
